package com.yanyu.space.common.db;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.yanyu.space.common.core.bootlog.BootstrapLogContext;
import com.yanyu.space.common.core.constants.SpaceConstants;
import com.yanyu.space.common.core.yaml.YamlPropertySourceFactory;
import com.yanyu.space.common.db.config.MetaObjectHandlerConfig;
import com.yanyu.space.common.db.config.PageInterceptorConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @author yanyu
 */
@Configuration
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:" + SpaceConstants.Properties.DB_PROP)
@MapperScan(value = SpaceConstants.CorePackage.SPACE_DAO)
public class MybatisAutoConfig {

    public MybatisAutoConfig() {
        BootstrapLogContext.put("db", "开启db功能");
    }

    @Bean
    @ConditionalOnMissingBean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        // 定义mybatisPlus拦截器
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        // 设置请求的页面大于最大业后操作，true调回到首页，false继续请求，默认为fasle
        paginationInterceptor.setOverflow(true);
        // 设置最大单页限制数量，默认500， -1 不受限制
        paginationInterceptor.setMaxLimit(500L);
        // 分页
        interceptor.addInnerInterceptor(paginationInterceptor);

        // 乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        // 防止更新与删除
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }

    @Bean
    @ConditionalOnMissingBean
    public PageInterceptorConfig pageInterceptorConfig() {
        return new PageInterceptorConfig();
    }

    @Bean
    @ConditionalOnMissingBean
    public MetaObjectHandlerConfig metaObjectHandlerConfig() {
        return new MetaObjectHandlerConfig();
    }
}
